package com.cqupt.slewing

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject


const val CHANNEL_ID = "Slewing Channel ID"

class MyService : LifecycleService() {
    private lateinit var session: String

    override fun onCreate() {
        super.onCreate()
        // 初始化通知通道
        createChannel()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        session = intent?.getStringExtra("session").toString()
        val macList = intent?.getStringArrayListExtra("mac")
        var tempMac = ""


        lifecycleScope.launch {
            while (true) {
                delay(5000)
                if (macList != null) {
                    for (mac in macList) {
                        val location = getLocation("/device/get_location/$mac")
                        if (location[0] < -20 || location[0] > 20 || location[1] < -20 || location[1] > 20) {
                            tempMac = mac
                            val notification: Notification =
                                Notification.Builder(this@MyService, CHANNEL_ID)
                                    .setContentTitle(mac)
                                    .setContentText("Warning, this item has been lost!")
                                    .setSmallIcon(R.drawable.ic_warning)
                                    .build()
                            // 显示通知
                            with(NotificationManagerCompat.from(this@MyService)) {
                                // notificationId is a unique int for each notification that you must define
                                notify(1, notification)
                            }
                        }
                    }
                    macList.remove(tempMac)
                }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }


    private fun createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel
            val name = "Slewing Notification"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
        }
    }


    private suspend fun getLocation(urlString: String): List<Double> {
        var x = 0.0
        var y = 0.0
        val client = OkHttpClient()
        val request: Request = Request.Builder()
            .url(MyRepository.HOST + urlString)
            .addHeader("cookie", session)
            .build()

        withContext(Dispatchers.IO) {
            val response = client.newCall(request).execute()
            val tempResponse = response.body?.string()
            Log.d("myTAG", "getData: $tempResponse")
            val json = JSONObject(tempResponse)
            x = json.getDouble("x")
            y = json.getDouble("y")
        }
        return listOf(x, y)
    }
}